/*
 *                    BioJava development code
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  If you do not have a copy,
 * see:
 *
 *      http://www.gnu.org/copyleft/lesser.html
 *
 * Copyright for this code is held jointly by the individual
 * authors.  These should be listed in @author doc comments.
 *
 * For more information on the BioJava project and its aims,
 * or to join the biojava-l mailing list, visit the home page
 * at:
 *
 *      http://www.biojava.org/
 *
 * Created on 15.08.2007
 * @author Asia Grzibovska
 *
 */

package uk.ac.sanger.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

import org.xml.sax.*;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import uk.ac.sanger.*;

/**
 * Servlet implementation class for Servlet: AsjaTestServlet
 *
 */

public class WritebackDatabase extends HttpServlet implements Servlet {
	
	// Instantiate this class to provide handlers for the parser and 
	// tell the parser about the handlers
	WritebackXMLParser handler = new WritebackXMLParser();
	public static boolean error =false;
	
	DataManagerInterface dbM = new DataManager();

	public void init(ServletConfig config)
	throws ServletException
	{
		super.init(config);
	}

	//	This is the all-important doPost() method!
	public void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
				//call XML parser
				FeatureBean[] features = handleParser(request,response);
				
				String reply="";
				//save data in db
				if (!features[0].getUpdate().equals("NA"))
					reply=dbM.updateFeature(features, features[0].getSystem_uri());	
				else if (!features[0].getDelete().equals("NA"))
					reply=dbM.deleteFeature(features, features[0].getSystem_uri());
				else {
					reply=dbM.saveFeature(features, features[0].getSystem_uri());	
				}
				
				ServletOutputStream outStream =	response.getOutputStream();
				outStream.println(reply);
		}
		catch (Exception err){
			err.printStackTrace(); 
			ServletOutputStream outStream =	response.getOutputStream();
			outStream.println("error"+err.getMessage());}
	}

	public void doGet(HttpServletRequest request,
			HttpServletResponse response)
	throws IOException, ServletException
	{
		try
		{
			response.setContentType("text/html");
			PrintWriter out = response.getWriter( );
			out.println ("<html><body>WritebackDatabase</body></html>");
			out.println("<HTML><HEAD><TITLE>Servlet</TITLE></HEAD></HTML>");
		}
		catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e.getMessage());
		}
	}

	public FeatureBean[] handleParser(HttpServletRequest request,
			HttpServletResponse response) throws IOException, SAXException {

		BufferedReader reader = new BufferedReader(new
				InputStreamReader(request.getInputStream()));
		ServletOutputStream outStream =	response.getOutputStream();
		String XMLsource ="";

		String message = null;
		boolean gotMessage = false;
		while ((message = reader.readLine()) != null) {
//			System.out.println("writeback got: "+message);
			// get XML data from input stream, store in XMLsource String-variable
			XMLsource=XMLsource+message;
			gotMessage = true;	}
		if (!gotMessage)
			outStream.println("Got no message");	
		
		// Create the parser we'll use.  The parser implementation is a 
		// Xerces class, but we use it only through the SAX XMLReader API
		org.xml.sax.XMLReader parser=new org.apache.xerces.parsers.SAXParser();

		// Specify that we don't want validation.  This is the SAX2
		// API for requesting parser features.  Note the use of a
		// globally unique URL as the feature name.  Non-validation is
		// actually the default, so this line isn't really necessary.
		parser.setFeature("http://xml.org/sax/features/validation", false);
		parser.setContentHandler(handler);
		parser.setErrorHandler(handler);		
		// Send XML string to XMLTester4 to perform parsing.
		// Then tell the parser to parse input from that source
		org.xml.sax.InputSource input=new InputSource(new StringBufferInputStream(XMLsource));
		parser.parse(input);
		FeatureBean[] features = handler.getFeatures(); 
		
		return features;
	}

}

